package com.shudai.largescreen.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.shudai.largescreen.mapper.RepurchaseAnalysisMapper;
import com.shudai.largescreen.pojo.vo.*;
import com.shudai.largescreen.service.RepurchaseAnalysisService;
import com.shudai.largescreen.util.DateQuery;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@RequiredArgsConstructor
@Slf4j
public class RepurchaseAnalysisServiceImpl implements RepurchaseAnalysisService {

    private final RepurchaseAnalysisMapper repurchaseAnalysisMapper;

    @Override
    public Map<String, Object> getAllDeal() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String mothStartLastLast = DateQuery.getMothStart3();
        LocalDateTime parse = LocalDateTime.parse(mothStartLastLast, df);
        LocalDateTime endTime = LocalDateTime.parse(DateQuery.getMothStart(), df);
        //查询下单总金额 总人数 AllCityAmount
        AllCityAmount allCityAmount = repurchaseAnalysisMapper.findAllAount(parse);
        //查询3个月用户下单id ,金额
        List<AllCityAmount > userIds = repurchaseAnalysisMapper.findUserRecord(parse);
        List<Long> collect = userIds.stream().map(AllCityAmount::getId).collect(Collectors.toList());
        //查询之前是否下单
        List<AllCityAmount > rate = repurchaseAnalysisMapper.findUserRecordRate(collect,parse,endTime);
        List<AllCityAmount> collect1 = rate.stream().filter(x -> Integer.parseInt(x.getTotal()) > 0).collect(Collectors.toList());
        int total = 0;
        for (AllCityAmount cityAmount : collect1) {
            for (AllCityAmount userId : userIds) {
                if (cityAmount.getId().equals(userId.getId())){
                    total+=userId.getFinish();
                }
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("customerUnitTotal",allCityAmount.getFinish()/Integer.parseInt(allCityAmount.getTotal()));
        map.put("repurchaseTotal",total);
        return map;
    }

    @Override
    public List<SalesmanRepurchaseVo> getSalesmanRepurchase(String province, String region) {
        if (StringUtils.isEmpty(province) && StringUtils.isEmpty(region)) {
            province = "广东省";
            region = "深圳市";
        }

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String mothStartLastLast = DateQuery.getMothStart3();
        String mothStart = DateQuery.getMothStart();
        LocalDateTime startDate = LocalDateTime.parse(mothStartLastLast, df);
        LocalDateTime endDate = LocalDateTime.parse(mothStart, df);

        //查询业务员入职时间 姓名
        List<SalesmanRepurchaseVo> salesmanRepurchaseVo = repurchaseAnalysisMapper.findSalesMan(province,region);

        List<SalesmanRepurchaseVo> salesmanRepurchaseVoList = new ArrayList<>();
        for (SalesmanRepurchaseVo repurchaseVo : salesmanRepurchaseVo) {
            //查销售人员下这三个月下单用户
            List<SalesmanRepurchaseVo> salesmanRepurchaseVos =  repurchaseAnalysisMapper.findAllUserRecordIds(repurchaseVo.getId(),startDate,endDate);
            if (CollectionUtils.isNotEmpty(salesmanRepurchaseVos)){
                //查之前是否有过下单得到数量
                List<Long> collect = salesmanRepurchaseVos.stream().map(SalesmanRepurchaseVo::getUserRecordId).collect(Collectors.toList());
                List<AllCityAmount> userRe = repurchaseAnalysisMapper.findUserRecordRate(collect,startDate,endDate);
                List<AllCityAmount> collect1 = userRe.stream().filter(x -> Integer.parseInt(x.getTotal()) > 1).collect(Collectors.toList());
                SalesmanRepurchaseVo salesmanRepurchaseVo1 = new SalesmanRepurchaseVo();

                salesmanRepurchaseVo1.setSalesman(repurchaseVo.getSalesman());
                salesmanRepurchaseVo1.setEntryTime(repurchaseVo.getEntryTime());
                salesmanRepurchaseVo1.setId(repurchaseVo.getId());
                salesmanRepurchaseVo1.setTimeRangeStart(startDate);
                salesmanRepurchaseVo1.setTimeRangeEnd(endDate);
                //成交客户数
                long count = salesmanRepurchaseVos.stream().mapToLong(SalesmanRepurchaseVo::getPurchaseCustomerNumber).count();

                salesmanRepurchaseVo1.setPurchaseCustomerNumber(count);


                int repurchaseCustomerNumber = 0;// 复购 复购
                int  repurchaseNumber = 0; //复购 客户

                for (SalesmanRepurchaseVo vo : salesmanRepurchaseVos) {
                    for (AllCityAmount allCityAmount : collect1) {
                        if (allCityAmount.getId().equals(vo.getUserRecordId())){
                            repurchaseNumber++;
                            repurchaseCustomerNumber+=vo.getRepurchaseNumber();

                        }
                    }
                }
                salesmanRepurchaseVo1.setRepurchaseCustomerNumber(repurchaseCustomerNumber);
                salesmanRepurchaseVo1.setRepurchaseNumber(repurchaseNumber);
                salesmanRepurchaseVo1.setRepurchaseRate(new BigDecimal(repurchaseNumber).divide(new BigDecimal(salesmanRepurchaseVos.size()),2, RoundingMode.HALF_UP));
                salesmanRepurchaseVoList.add(salesmanRepurchaseVo1);
            }else {
                SalesmanRepurchaseVo salesmanRepurchaseVo1 = new SalesmanRepurchaseVo();

                salesmanRepurchaseVo1.setSalesman(repurchaseVo.getSalesman());
                salesmanRepurchaseVo1.setEntryTime(repurchaseVo.getEntryTime());
                salesmanRepurchaseVo1.setId(repurchaseVo.getId());
                salesmanRepurchaseVo1.setTimeRangeStart(startDate);
                salesmanRepurchaseVo1.setTimeRangeEnd(endDate);
                salesmanRepurchaseVo1.setRepurchaseCustomerNumber(0);
                salesmanRepurchaseVo1.setRepurchaseNumber(0);
                salesmanRepurchaseVo1.setRepurchaseRate(new BigDecimal(0));
                salesmanRepurchaseVo1.setPurchaseCustomerNumber(0L);
                salesmanRepurchaseVoList.add(salesmanRepurchaseVo1);

            }
        }
        List<SalesmanRepurchaseVo> collect = salesmanRepurchaseVoList.stream().sorted(Comparator.comparing(SalesmanRepurchaseVo::getRepurchaseRate).reversed()).collect(Collectors.toList());


        return collect;
    }

    @Override
    public Map<String, Object> getTeamRepurchase(String province, String region,String teamName) {
        if (StringUtils.isEmpty(province) && StringUtils.isEmpty(region)) {
            province = "广东省";
            region = "深圳市";
        }
        //查询订单收货地址
//        repurchaseAnalysisMapper.findUserRecordRate() 8月
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String mothStartLastLast = DateQuery.getMothStartLast2();
        String mothStartLsatLast = DateQuery.getMothEndLast2();
        LocalDateTime startDateLastLast = LocalDateTime.parse(mothStartLastLast, df);
        LocalDateTime endDateLastLast = LocalDateTime.parse(mothStartLsatLast, df);
        String mothLastLast = (Integer.parseInt((DateTime.now() + "").split(" ")[0].split("-")[1])-2) + "月";
        TeamRepurchase rateLastLast = getRate(province, region, startDateLastLast, endDateLastLast, mothLastLast,teamName);

        //9月
        LocalDateTime startDateLast = LocalDateTime.parse(DateQuery.getMothStartLast(), df);
        LocalDateTime endDateLast = LocalDateTime.parse(DateQuery.getMothEndLast(), df);
        String mothLast = (Integer.parseInt((DateTime.now() + "").split(" ")[0].split("-")[1])-1) + "月";
        TeamRepurchase rateLast = getRate(province, region, startDateLast, endDateLast, mothLast,teamName);
        //10月
        LocalDateTime endTime = LocalDateTime.parse(DateQuery.getMothEnd(), df);
        LocalDateTime startTime = LocalDateTime.parse(DateQuery.getMothStart(), df);
        String moth = (Integer.parseInt((DateTime.now() + "").split(" ")[0].split("-")[1])) + "月";
        TeamRepurchase rate = getRate(province, region, startTime, endTime, moth,teamName);
        List<TeamRepurchase> list = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(rateLastLast)){
            list.add(rateLastLast);
        }else {
            TeamRepurchase teamRepurchase = new TeamRepurchase();
            teamRepurchase.setCurrent(0);
            teamRepurchase.setMonth(mothLastLast);
            teamRepurchase.setPercent(new BigDecimal(0));
            teamRepurchase.setRepurchaseMoney(0);
            teamRepurchase.setRepurchaseNumber(0);
            teamRepurchase.setRepurchaseRate(new BigDecimal(0));
            teamRepurchase.setTarget(0);
            teamRepurchase.setNoRepurchaseRate(new BigDecimal(0));

            list.add(teamRepurchase);
        }
        if (ObjectUtils.isNotEmpty(rateLast)){
            list.add(rateLast);
        }else {
            TeamRepurchase teamRepurchase = new TeamRepurchase();
            teamRepurchase.setCurrent(0);
            teamRepurchase.setMonth(mothLast);
            teamRepurchase.setPercent(new BigDecimal(0));
            teamRepurchase.setRepurchaseMoney(0);
            teamRepurchase.setRepurchaseNumber(0);
            teamRepurchase.setRepurchaseRate(new BigDecimal(0));
            teamRepurchase.setTarget(0);
            teamRepurchase.setNoRepurchaseRate(new BigDecimal(0));

            list.add(teamRepurchase);
        }
        if (ObjectUtils.isNotEmpty(rate)){
            list.add(rate);
        }else {
            TeamRepurchase teamRepurchase = new TeamRepurchase();
            teamRepurchase.setCurrent(0);
            teamRepurchase.setMonth(moth);
            teamRepurchase.setPercent(new BigDecimal(0));
            teamRepurchase.setRepurchaseMoney(0);
            teamRepurchase.setRepurchaseNumber(0);
            teamRepurchase.setRepurchaseRate(new BigDecimal(0));
            teamRepurchase.setTarget(0);
            teamRepurchase.setNoRepurchaseRate(new BigDecimal(0));

            list.add(teamRepurchase);
        }


        TotalStaticVo  totalStaticVo = new TotalStaticVo();
        totalStaticVo.setPurchaseCustomer(0);
        totalStaticVo.setRepurchaseCustomer(0);
        totalStaticVo.setRepurchaseMoney(0);
        totalStaticVo.setRepurchaseRate(new BigDecimal(0));
        totalStaticVo.setRepurchaseNumber(0);
        totalStaticVo.setNoRepurchaseRate(new BigDecimal(0));
        totalStaticVo.setNoRepurchaseCustomer(0);

        //三月合计
        if (ObjectUtils.isNotEmpty(rateLastLast) || ObjectUtils.isNotEmpty(rateLast) || ObjectUtils.isNotEmpty(rate)){
            TeamRepurchase teamRepurchase1 = new TeamRepurchase();
            TeamRepurchase teamRepurchase2 = new TeamRepurchase();
            TeamRepurchase teamRepurchase3 = new TeamRepurchase();
            if (ObjectUtils.isEmpty(rateLastLast)){

                teamRepurchase1.setRepurchaseNumber(0);
                teamRepurchase1.setRepurchaseMoney(0);
                teamRepurchase1.setTarget(0);
                teamRepurchase1.setCurrent(0);
            }else {

                teamRepurchase1.setRepurchaseNumber(rateLastLast.getRepurchaseNumber());
                teamRepurchase1.setRepurchaseMoney(rateLastLast.getRepurchaseMoney());
                teamRepurchase1.setTarget(rateLastLast.getTarget());
                teamRepurchase1.setCurrent(rateLastLast.getCurrent());
            }
            if (ObjectUtils.isEmpty(rateLast)){

                teamRepurchase2.setRepurchaseNumber(0);
                teamRepurchase2.setRepurchaseMoney(0);
                teamRepurchase2.setTarget(0);
                teamRepurchase2.setCurrent(0);
            }else {

                teamRepurchase2.setRepurchaseNumber(rateLast.getRepurchaseNumber());
                teamRepurchase2.setRepurchaseMoney(rateLast.getRepurchaseMoney());
                teamRepurchase2.setTarget(rateLast.getTarget());
                teamRepurchase2.setCurrent(rateLast.getCurrent());
            }

            if (ObjectUtils.isEmpty(rate)){
                teamRepurchase3.setRepurchaseNumber(0);
                teamRepurchase3.setRepurchaseMoney(0);
                teamRepurchase3.setTarget(0);
                teamRepurchase3.setCurrent(0);
            }else {

                teamRepurchase3.setRepurchaseNumber(rateLastLast.getRepurchaseNumber());
                teamRepurchase3.setRepurchaseMoney(rateLastLast.getRepurchaseMoney());
                teamRepurchase3.setTarget(rateLastLast.getTarget());
                teamRepurchase3.setCurrent(rateLastLast.getCurrent());
            }
            //复购件数
            int totalNumber = teamRepurchase3.getRepurchaseNumber()+teamRepurchase2.getRepurchaseNumber()+teamRepurchase1.getRepurchaseNumber();
            //复购金额
            int totalAmount =teamRepurchase2.getRepurchaseMoney()+teamRepurchase3.getRepurchaseMoney()+teamRepurchase1.getRepurchaseMoney();
            //成交客户
            int target =teamRepurchase2.getTarget()+teamRepurchase3.getTarget()+teamRepurchase1.getTarget();
            //复购客户
            int current = teamRepurchase2.getCurrent()+teamRepurchase3.getCurrent()+teamRepurchase1.getCurrent();
            //复购率
            BigDecimal rates = new BigDecimal(0);
            if (target != 0){
                rates= new BigDecimal(current).divide(new BigDecimal(target),2, RoundingMode.HALF_UP);
            }


            totalStaticVo.setPurchaseCustomer(target);
            totalStaticVo.setRepurchaseCustomer(current);
            totalStaticVo.setRepurchaseMoney(totalAmount);
            totalStaticVo.setRepurchaseRate(rates);
            totalStaticVo.setRepurchaseNumber(totalNumber);
            totalStaticVo.setNoRepurchaseRate(new BigDecimal(1).subtract(rates));
            totalStaticVo.setNoRepurchaseCustomer(target-current);
        }




        Map<String , Object> map = new HashMap<>();
        if (StringUtils.isNotEmpty(province) && StringUtils.isEmpty(region)){
            region = province;
        }
        if (StringUtils.isNotEmpty(teamName)){
            region = teamName;
        }
        map.put("city",region);
        map.put("totalStatic",totalStaticVo);
        map.put("chartsData",list);

        return map;
    }

    public TeamRepurchase getRate(String province,String region,LocalDateTime startDate,LocalDateTime endDate,String moth,String teamName){
        //8月 获取两个月前的时间

        //查询8月购买人 id
        List<SalesmanRepurchaseVo> timesUserRecord = repurchaseAnalysisMapper.findTimesUserRecord(startDate, endDate,province,region,teamName);
        //判断之前是否下单
        List<Long> collect = timesUserRecord.stream().map(SalesmanRepurchaseVo::getUserRecordId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect)){

            List<AllCityAmount> userRecordRate = repurchaseAnalysisMapper.findUserRecordRate(collect, startDate, endDate);
            List<AllCityAmount> collect1 = userRecordRate.stream().filter(x -> Integer.parseInt(x.getTotal()) > 1).collect(Collectors.toList());


            //SELECT o.user_record_id id ,count(o.id) total  FROM sd_order o where o.order_state in(2,3,12)   and o.user_record_id in      and o.order_time BETWEEN ? and ?   GROUP BY o.user_record_id
            //### Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'and o.order_time BETWEEN '2022-08-01 00:00:00' and '2022-08-31 00:00:00'   GROUP' at line 1
            //; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'and o.order_time BETWEEN '2022-08-01 00:00:00' and '2022-08-31 00:00:00'   GROUP' at line 1] with root cause

            //件数
            Integer totalNUmber = 0;
            //金额
            Integer totalAmount = 0;
            for (SalesmanRepurchaseVo salesmanRepurchaseVo : timesUserRecord) {
                for (AllCityAmount allCityAmount : collect1) {
                    if (salesmanRepurchaseVo.getUserRecordId().equals(allCityAmount.getId())){
                        totalNUmber+=salesmanRepurchaseVo.getRepurchaseCustomerNumber();
                        totalAmount+=salesmanRepurchaseVo.getRepurchaseNumber();
                    }
                }
            }
            BigDecimal rate = new BigDecimal(0);
            if (timesUserRecord.size() != 0){
                //复购率
                rate= new BigDecimal(collect1.size()).divide(new BigDecimal(timesUserRecord.size()),2, RoundingMode.HALF_UP);
            }

            TeamRepurchase teamRepurchase = new TeamRepurchase();
            teamRepurchase.setCurrent(collect1.size());
            teamRepurchase.setMonth(moth);
            teamRepurchase.setPercent(rate);
            teamRepurchase.setRepurchaseMoney(totalAmount);
            teamRepurchase.setRepurchaseNumber(totalNUmber);
            teamRepurchase.setRepurchaseRate(rate);
            teamRepurchase.setTarget(timesUserRecord.size());
            teamRepurchase.setNoRepurchaseRate(new BigDecimal(1).subtract(rate));
            return teamRepurchase;
        }
            TeamRepurchase teamRepurchase = new TeamRepurchase();
            teamRepurchase.setCurrent(0);
            teamRepurchase.setMonth(moth);
            teamRepurchase.setPercent(new BigDecimal(0));
            teamRepurchase.setRepurchaseMoney(0);
            teamRepurchase.setRepurchaseNumber(0);
            teamRepurchase.setRepurchaseRate(new BigDecimal(0));
            teamRepurchase.setTarget(0);
            teamRepurchase.setNoRepurchaseRate(new BigDecimal(0));
            return teamRepurchase;


//        return null;

    }

    @Override
    public Map<String, Object> getTeamCustomerUnit(String province, String region) {

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //8月
        String mothStartLastLast = DateQuery.getMothStartLast2();
        String mothStartLsatLast = DateQuery.getMothEndLast2();
        LocalDateTime startDateLastLast = LocalDateTime.parse(mothStartLastLast, df);
        LocalDateTime endDateLastLast = LocalDateTime.parse(mothStartLsatLast, df);
        String mothLastLast = (Integer.parseInt((DateTime.now() + "").split(" ")[0].split("-")[1])-2) + "月";
        List<Map<String, Object>> unit = getUnit(province, region, startDateLastLast, endDateLastLast, mothLastLast);

        //9月
        LocalDateTime startDateLast = LocalDateTime.parse(DateQuery.getMothStartLast(), df);
        LocalDateTime endDateLast = LocalDateTime.parse(DateQuery.getMothEndLast(), df);
        String mothLast = (Integer.parseInt((DateTime.now() + "").split(" ")[0].split("-")[1])-1) + "月";
        List<Map<String, Object>> unit1 = getUnit(province, region, startDateLast, endDateLast, mothLast);

        //10月
        LocalDateTime endTime = LocalDateTime.parse(DateQuery.getMothEnd(), df);
        LocalDateTime startTime = LocalDateTime.parse(DateQuery.getMothStart(), df);
        String moth = (Integer.parseInt((DateTime.now() + "").split(" ")[0].split("-")[1])) + "月";
        List<Map<String, Object>> unit2 = getUnit(province, region, startTime, endTime, moth);

        //合计
        //总客户
        int totalNumber =  (int)unit.get(0).get("value")+(int)unit1.get(0).get("value")+(int)unit2.get(0).get("value");
        int totalMoney =  (int)unit.get(1).get("value")+(int)unit1.get(1).get("value")+(int)unit2.get(1).get("value");
        //单价
        int rate = 0;
        if (totalNumber!=0){
            rate = totalMoney/totalNumber;
        }
        Map<String, Object> objectMap = new HashMap<>();
        objectMap.put("title","合计");
        objectMap.put("type","group");

        Map<String , Object> numMap = new HashMap<>();
        numMap.put("title","客户数");
        numMap.put("value",totalNumber);
        numMap.put("type","item");
        Map<String , Object> moneyMap = new HashMap<>();
        moneyMap.put("title","总金额");
        moneyMap.put("value",totalMoney);
        moneyMap.put("type","item");
        Map<String , Object> oneMap = new HashMap<>();
        oneMap.put("title","客单价");
        oneMap.put("value",rate);
        oneMap.put("type","item");

        List<Map<String, Object>> unit3 = new ArrayList<>();
        List<Map<String, Object>> unit4 = new ArrayList<>();
        List<Map<String, Object>> unit5 = new ArrayList<>();


        Map<String , Object> numMap1 = new HashMap<>();
        numMap1.put("title",unit.get(0).get("title"));
        numMap1.put("value",unit.get(0).get("value"));
        numMap1.put("type","item");
        Map<String , Object> numMap2 = new HashMap<>();
        numMap2.put("title",unit1.get(0).get("title"));
        numMap2.put("value",unit1.get(0).get("value"));
        numMap2.put("type","item");
        Map<String , Object> numMap3 = new HashMap<>();
        numMap3.put("title",unit2.get(0).get("title"));
        numMap3.put("value",unit2.get(0).get("value"));
        numMap3.put("type","item");
        unit3.add(numMap1);
        unit3.add(numMap2);
        unit3.add(numMap3);


        Map<String , Object> numMap4 = new HashMap<>();
        numMap4.put("title",unit.get(1).get("title"));
        numMap4.put("value",unit.get(1).get("value"));
        numMap4.put("type","item");
        Map<String , Object> numMap5 = new HashMap<>();
        numMap5.put("title",unit1.get(1).get("title"));
        numMap5.put("value",unit1.get(1).get("value"));
        numMap5.put("type","item");
        Map<String , Object> numMap6 = new HashMap<>();
        numMap6.put("title",unit2.get(1).get("title"));
        numMap6.put("value",unit2.get(1).get("value"));
        numMap6.put("type","item");
        unit4.add(numMap4);
        unit4.add(numMap5);
        unit4.add(numMap6);

        Map<String , Object> numMap7 = new HashMap<>();
        numMap7.put("title",unit.get(2).get("title"));
        numMap7.put("value",unit.get(2).get("value"));
        numMap7.put("type","item");
        Map<String , Object> numMap8 = new HashMap<>();
        numMap8.put("title",unit1.get(2).get("title"));
        numMap8.put("value",unit1.get(2).get("value"));
        numMap8.put("type","item");
        Map<String , Object> numMap9 = new HashMap<>();
        numMap9.put("title",unit2.get(2).get("title"));
        numMap9.put("value",unit2.get(2).get("value"));
        numMap9.put("type","item");
        unit5.add(numMap7);
        unit5.add(numMap8);
        unit5.add(numMap9);




//        List<Map<String, Object>> descItems = Stream.of(unit, unit1, unit2).flatMap(Collection::stream).collect(Collectors.toList());
        List<Map<String, Object>> descItems = Stream.of(unit3, unit4, unit5).flatMap(Collection::stream).collect(Collectors.toList());
        descItems.add(objectMap);
        descItems.add(numMap);
        descItems.add(moneyMap);
        descItems.add(oneMap);


        List<Map<String, Object>> chartData = new ArrayList<>();
        Map<String, Object> orders = getOrders(province, region, startDateLastLast, endDateLastLast, mothLastLast);
        Map<String, Object> orders1 = getOrders(province, region, startDateLast, endDateLast, mothLast);
        Map<String, Object> orders2 = getOrders(province, region, startTime, endTime, moth);
        chartData.add(orders);
        chartData.add(orders1);
        chartData.add(orders2);

        Map<String,Object> stringObjectMap = new HashMap<>();
        if (StringUtils.isEmpty(region) && StringUtils.isEmpty(province)){
            region = "全国";
        }
        if (StringUtils.isEmpty(region) && StringUtils.isNotEmpty(province)){
            region =province;
        }
        stringObjectMap.put("city",region);
        stringObjectMap.put("descItems",descItems);
        stringObjectMap.put("chartData",chartData);

        return stringObjectMap;
    }

    public List<Map<String , Object>> getUnit(String province, String region,LocalDateTime startDate,LocalDateTime endDate,String name){
        //查询8月客户数量
        Integer numberTotal = repurchaseAnalysisMapper.findUserNumber(province,region,startDate,endDate);
        //查询8月总金额
        Integer moneyTotal = repurchaseAnalysisMapper.findUserMoney(province,region,startDate,endDate);

        //客单价
        int totalOne = 0;
        if (numberTotal != null && moneyTotal!= null){
            totalOne = moneyTotal/numberTotal;
        }
       Map<String , Object> numMap = new HashMap<>();
        numMap.put("title",name+"客户数");
        if (numberTotal != null){
            numMap.put("value",numberTotal);
        }else {
            numMap.put("value",0);
        }

        numMap.put("type","item");
        Map<String , Object> moneyMap = new HashMap<>();
        moneyMap.put("title",name+"总金额");
        if (moneyTotal != null){
            moneyMap.put("value",moneyTotal);
        }else {
            moneyMap.put("value",0);
        }

        moneyMap.put("type","item");
        Map<String , Object> oneMap = new HashMap<>();
        oneMap.put("title",name+"客单价");
        oneMap.put("value",totalOne);
        oneMap.put("type","item");

        List<Map<String , Object>> list = new ArrayList<>();
        list.add(numMap);
        list.add(moneyMap);
        list.add(oneMap);
        return list;
    }


    public Map<String , Object> getOrders(String province, String region,LocalDateTime startDate,LocalDateTime endDate,String name){
        //查询8月客户数量
        int numberTotal = repurchaseAnalysisMapper.findUserNumber(province,region,startDate,endDate);
        //查询8月订单数
        int moneyTotal = repurchaseAnalysisMapper.findUserM(province,region,startDate,endDate);

        Map<String , Object> numMap = new HashMap<>();
        numMap.put("title",name);
        numMap.put("data1",numberTotal);
        numMap.put("data2",moneyTotal);

        return numMap;
    }

    @Override
    public Map<String, Object> getThreeMonthTotal() {
        //定一个总数
        int targert = 500;
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //8月
        LocalDateTime start = LocalDateTime.parse(DateQuery.getMothStartLast2(), df);
        LocalDateTime endTime = LocalDateTime.parse(DateQuery.getMothEnd(), df);
//        repurchaseAnalysisMapper.find
        TeamRepurchase rate = getRate(null, null, start, endTime, null,null);
        //复购客户数
        Integer current = rate.getCurrent();
        //复购率
        BigDecimal repurchaseRate = rate.getRepurchaseRate();
        //成交客户数
        int target = rate.getTarget();

        Map<String,Object> map = new HashMap<>();
        map.put("finish",target);
        map.put("finishRate",new BigDecimal(target).divide(new BigDecimal(targert),2, RoundingMode.HALF_UP));
        map.put("repurchase",current);
        map.put("totalRepurchase",current);
        map.put("repurchaseRate",new BigDecimal(1).subtract(repurchaseRate));

        return map;
    }

    @Override
    public Map<String,Object>  getNoRepurchaseTable(String province, String region) {
        List<NoRepurchaseTable> noList = new ArrayList<>();
        List<SalesmanRepurchaseVo> salesmanRepurchase = getSalesmanRepurchase(province, region);
        //查出地址和部门
        List<Long> collect = salesmanRepurchase.stream().map(SalesmanRepurchaseVo::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect)){

            List<NoRepurchaseTable> noRepurchaseTables =repurchaseAnalysisMapper.findSalesManDetail(collect);
            for (SalesmanRepurchaseVo salesmanRepurchaseVo : salesmanRepurchase) {

                for (NoRepurchaseTable noRepurchaseTable : noRepurchaseTables) {
                    if (salesmanRepurchaseVo.getId().equals(noRepurchaseTable.getId())){
                        NoRepurchaseTable noRepurchaseTable1 = new NoRepurchaseTable();
                        //业务员名称
                        noRepurchaseTable1.setSalesman(noRepurchaseTable.getSalesman());
                        //时间
                        noRepurchaseTable1.setStartTime(salesmanRepurchaseVo.getTimeRangeStart());
                        noRepurchaseTable1.setEndTime(salesmanRepurchaseVo.getTimeRangeEnd());
                        //团队名称
                        noRepurchaseTable1.setTeam(noRepurchaseTable.getCity()+"-"+noRepurchaseTable.getDistrict() +"-"+noRepurchaseTable.getDeptName());
                        //成交客户数

                        if (salesmanRepurchaseVo.getPurchaseCustomerNumber() != null){
                            noRepurchaseTable1.setPurchaseCustomerNumber(salesmanRepurchaseVo.getPurchaseCustomerNumber());
                            //未复购客户
                            noRepurchaseTable1.setNoRepurchaseCustomerNumber(salesmanRepurchaseVo.getPurchaseCustomerNumber()-Long.parseLong(salesmanRepurchaseVo.getRepurchaseNumber()+""));
                            //未复购率
                            noRepurchaseTable1.setNoRepurchaseRate(new BigDecimal(1).subtract(salesmanRepurchaseVo.getRepurchaseRate()));

                        }else {
                            noRepurchaseTable1.setPurchaseCustomerNumber(0L);
                            //未复购客户
                            noRepurchaseTable1.setNoRepurchaseCustomerNumber(0L);
                            //未复购率
                            noRepurchaseTable1.setNoRepurchaseRate(new BigDecimal(0));

                        }

                             noList.add(noRepurchaseTable1);
                    }
                }
        }

        }

        Map<String,Object> objectMap = new HashMap<>();
        objectMap.put("chartData",noList);

        return objectMap;
    }

    @Override
    public Map<String, Object> getTeamNoRepurchaseTable(String province, String region,String teamName) {

        return  getTeamRepurchase(province, region,teamName);
    }
}
